
package Chat;

import Client.I_ChatClient;
import Serveur.I_chat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;


public class InterfacePrincipale extends javax.swing.JFrame {
    private String login;
    private I_chat sha;
    private DefaultListModel dl;
    private ArrayList<String> historique;
    private int nbClient;
    /**
     * Creates new form InterfacePrincipale
     */
    public InterfacePrincipale(I_chat chatCourant, String login) {
        this.login=login;
        this.sha = chatCourant;
        historique = new ArrayList<String>();
        InterfacePrincipale.this.setTitle("Discussion en cours");
        initComponents();
        this.jTextAreaAffichageMessages.setEditable(false);
        this.jTextAreaEcrirePublic.requestFocus();
        this.dl = new DefaultListModel();
        actualiserListeUtilisateur();
        javax.swing.Timer t = new javax.swing.Timer(1000, new majChat());
        t.start();
    }
    
    /** Actualise l'affichage des noms des utilisateurs connectés au chat
     */
    private void actualiserListeUtilisateur(){
        //Réinitialise la liste
        try {
            dl.removeAllElements();
            for (int i = 0; i < sha.clientsDisponibles().size(); i++) {
                //Si le login n'est pas celui de l'utilisateur et si le nom n'est pas deja dans la liste
                if(!login.equals(sha.clientsDisponibles().get(i).getNomClient()) && !dl.contains(sha.clientsDisponibles().get(i).getNomClient())){
                    dl.addElement(sha.clientsDisponibles().get(i).getNomClient());
                }
            }
            this.jListConnectes.setModel(dl);
        } catch (RemoteException ex) {
            Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void actualiserChat() throws RemoteException{
        historique = sha.retourHistorique();
        jTextAreaAffichageMessages.setText("");
        for(int i=0;i<historique.size();i++ ){
                jTextAreaAffichageMessages.append(historique.get(i)+"\n");
        }
    }
    
    /** Event d'actualisation du chat
     */
    class majChat implements ActionListener {
        @Override
    	public void actionPerformed(ActionEvent e) {
            try {
                InterfacePrincipale.this.actualiserChat();
                if(nbClient != sha.clientsDisponibles().size()){
                    InterfacePrincipale.this.actualiserListeUtilisateur();
                }
                nbClient = sha.clientsDisponibles().size();
            } 
            catch (RemoteException ex) {
                Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
            }
    	}
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPaneListeConnectes = new javax.swing.JScrollPane();
        jListConnectes = new javax.swing.JList();
        jScrollPaneAffichageMessages = new javax.swing.JScrollPane();
        jTextAreaAffichageMessages = new javax.swing.JTextArea();
        jButtonEnvoiGlobal = new javax.swing.JButton();
        jScrollPaneEcrirePublic = new javax.swing.JScrollPane();
        jTextAreaEcrirePublic = new javax.swing.JTextArea();
        Discuter = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jButtonDéco = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jScrollPaneListeConnectes.setViewportView(jListConnectes);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 40;
        gridBagConstraints.ipady = 300;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jScrollPaneListeConnectes, gridBagConstraints);

        jTextAreaAffichageMessages.setColumns(20);
        jTextAreaAffichageMessages.setRows(5);
        jScrollPaneAffichageMessages.setViewportView(jTextAreaAffichageMessages);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 300;
        gridBagConstraints.ipady = 200;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jScrollPaneAffichageMessages, gridBagConstraints);

        jButtonEnvoiGlobal.setText("Envoyer");
        jButtonEnvoiGlobal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEnvoiGlobalActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jButtonEnvoiGlobal, gridBagConstraints);

        jTextAreaEcrirePublic.setColumns(20);
        jTextAreaEcrirePublic.setRows(5);
        jScrollPaneEcrirePublic.setViewportView(jTextAreaEcrirePublic);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.ipadx = 300;
        gridBagConstraints.ipady = 30;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jScrollPaneEcrirePublic, gridBagConstraints);

        Discuter.setText("Discuter");
        Discuter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DiscuterActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(Discuter, gridBagConstraints);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel1.setText("Utilisateurs connectés :");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0);
        getContentPane().add(jLabel1, gridBagConstraints);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel2.setText("Discussion :");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0);
        getContentPane().add(jLabel2, gridBagConstraints);

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jSeparator1, gridBagConstraints);

        jButtonDéco.setText("Déconnexion");
        jButtonDéco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDécoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jButtonDéco, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonEnvoiGlobalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEnvoiGlobalActionPerformed
        try {
            //Récupère le message écrit par l'utilisateur du chat
            String message = jTextAreaEcrirePublic.getText();
            //envoi au(x) client(s) par écriture dans l'historique
            sha.envoyerMessage(message, login,'s');
            //Actualise le chat
            actualiserChat();
            jTextAreaEcrirePublic.setText("");
        } 
        catch (RemoteException ex) {
            Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonEnvoiGlobalActionPerformed
    
    private void DiscuterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DiscuterActionPerformed
        try{
        String destinataire = jListConnectes.getSelectedValue().toString();
        new InterfacePrivee(sha, destinataire, login).setVisible(true);
        }
        catch(Exception e){
            PopUp p = new PopUp("Veuillez selectionner une personne !");
            p.setVisible(true);
        }
    }//GEN-LAST:event_DiscuterActionPerformed

    private void jButtonDécoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDécoActionPerformed
        try {
            sha.envoyerMessage("s'est déconnecté", login,'h');
            actualiserChat();
            sha.deconnecter(login);
            InterfacePrincipale.this.dispose();
            new PageConnexion().setVisible(true);
        } catch (RemoteException ex) {
            Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonDécoActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Discuter;
    private javax.swing.JButton jButtonDéco;
    private javax.swing.JButton jButtonEnvoiGlobal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jListConnectes;
    private javax.swing.JScrollPane jScrollPaneAffichageMessages;
    private javax.swing.JScrollPane jScrollPaneEcrirePublic;
    private javax.swing.JScrollPane jScrollPaneListeConnectes;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTextAreaAffichageMessages;
    private javax.swing.JTextArea jTextAreaEcrirePublic;
    // End of variables declaration//GEN-END:variables
}
